//
//  XTRefreshView.swift
//  MyBlog
//
//  Created by victor on 17/4/6.
//  Copyright © 2017年 victor. All rights reserved.
//

import UIKit

/// 刷新视图 - 负责刷新相关的 UI 显示和动画
class XTRefreshView: UIView {

    /// 父视图的高度 - 为了刷新控件不需要关心当前具体的刷新视图是谁！
    var parentViewHeight: CGFloat = 0
    
    /// 指示器
    fileprivate lazy var indicator = UIActivityIndicatorView()
    /// 提示图标
    fileprivate lazy var tipIcon = UIImageView()
    /// 提示标签
    fileprivate lazy var tipLabel : UILabel = UILabel.cz_label(withText: "下拉开始刷新...", fontSize: 14, color: UIColor.darkGray)
    
    /// 刷新状态
    /**
     iOS 系统中 UIView 封装的旋转动画
     - 默认顺时针旋转
     - 就近原则
     - 要想实现同方向旋转，需要调整一个 非常小的数字(近)
     - 如果想实现 360 旋转，需要核心动画 CABaseAnimation
     */
    var refreshState: XTRefreshState = .Normal {
        didSet{
            switch refreshState {
            case .Normal:
                // 恢复状态
                tipIcon.isHidden = false
                indicator.stopAnimating()
                tipLabel.text = "继续使劲拉..."
                
                UIView.animate(withDuration: 0.25, animations: {
                    // 恢复到初始单位矩阵(默认状态)
                    self.tipIcon.transform = CGAffineTransform.identity
                })
            case .Pulling:
                tipLabel.text = "放手就刷新..."
                
                UIView.animate(withDuration: 0.25, animations: {
                    // +0.001 是逆时针 -0.001是顺时针旋转
                    self.tipIcon.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI + 0.001))
                })
            case .WillRefresh:
                tipLabel.text = "正在刷新中..."
                
                // 隐藏箭头
                tipIcon.isHidden = true
                
                // 显示菊花
                indicator.startAnimating()
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    fileprivate func setupUI() {
        tipIcon.image = UIImage(named: "tableview_pull_refresh")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        tipIcon.frame = CGRect(x: 0, y: 14, width: 32, height: 32)
        indicator.frame = CGRect(x: 6, y: 20, width: 20, height: 20)
        tipLabel.frame = CGRect(x: 40, y: 22, width: 98, height: 17)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
